const _ = require('lodash');

const prefix = '/api/message';
module.exports = app => {
    const {router, middleware} = app;

    /**消息列表*/
    router.get(prefix, middleware.api(), async ctx => {
        const {page, limit, offset} = ctx.service.page.page();
        let list, total;
        if (ctx.query.type === '0') {
            const {User} = ctx.app.model;
            const user = User.build({id: ctx.user.id});

            [total, list] = await Promise.all([
                user.countMyMessage(),
                app.model.UserMessage.findAll({
                    order: [['read', 'asc']],
                    include: [
                        {model: app.model.User, where: {id: ctx.user.id}},
                        {model: app.model.Message, include: [{model: app.model.User.unscoped(), as: 'from'}]},
                    ],
                }),
            ]);
            list = list.map(item => {
                return {
                    id: item.message.id,
                    title: item.message.title,
                    content: item.message.content,
                    created_at: item.message.created_at,
                    from: item.message.from,
                    read: item.read,
                };
            });
        } else {
            [total, list] = await Promise.all([
                app.model.Message.count({where: {from_id: ctx.user.id}}),
                app.model.Message.findAll({
                    limit,
                    offset,
                    raw: true,
                    order: [['id', 'desc']],
                    where: {from_id: ctx.user.id}
                }),
            ]);
            list.forEach(item => {
                item.from = {username: ctx.user.username};
            });
        }

        ctx.body = {list, total, page};
    });

    /**读取消息内容*/
    router.get(prefix + '/:message_id', middleware.api(), async ctx => {
        let message;
        if (ctx.query.type === '0') {
            const user = app.model.User.build({id: ctx.user.id}, {isNewRecord: false});
            message = await user.getMyMessage({where: {id: ctx.params.message_id}});

            if (message.length === 0)
                return ctx.helper.error('短消息不存在');

            message = message[0];

            //设置为已读
            if (!message.user_message.read)
                await message.user_message.update({read: true});

            ctx.service.message.updateUnreadMessage();
        } else {
            message = await app.model.Message.findOne({where: {id: ctx.params.message_id, from_id: ctx.user.id}});
            if (!message)
                return ctx.helper.error('短消息不存在');
        }

        ctx.body = message;
    });


    /**删除短消息*/
    router.del(prefix, middleware.api(), async ctx => {
        let {id} = ctx.query;
        if (_.isEmpty(id))
            return ctx.helper.error('ID为空');
        id = _(id.split(',')).uniq().compact().value();
        if (_.isEmpty(id))
            return ctx.helper.error('ID为空');
        let user = app.model.User.build({id: ctx.user.id}, {isNewRecord: false});
        let messages = await user.getMyMessage({where: {id: {[app.Sequelize.Op.in]: id}}});
        messages = messages.map(message => new Promise(resolve => {
            app.model.UserMessage.update({delete: true}, {
                where: {
                    user_id: ctx.user.id,
                    message_id: message.id
                }
            }).then(() => {
                resolve();
            });
        }));
        await Promise.all(messages);
        ctx.service.message.updateUnreadMessage();
        ctx.body = 'ok';
    });

    /**发短消息**/
    router.post(prefix, middleware.api(), async ctx => {
        let {title, content, users} = ctx.request.body;

        await ctx.service.message.send({from: ctx.user, to: users, title, content});
        ctx.body = 'ok';
    });
};